import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttk
import json
import sys

# 配置文件路径
config_file = 'config.json'

class ImageReplacerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("图片替换工具")
        self.root.geometry("600x200")
        
        # 状态码（类属性）
        self.exit_code = 0  # 默认失败
        
        # 默认路径
        self.source_dir = ""
        self.target_dir = ""
        
        self.setup_ui()
        self.load_config()
    
    def setup_ui(self):
        """设置用户界面"""
        main_frame = tk.Frame(self.root, padx=10, pady=10)
        main_frame.pack(expand=True, fill='both')
        
        # 源图片行
        source_frame = tk.Frame(main_frame)
        source_frame.pack(fill='x', pady=5, anchor='w')
        
        tk.Label(source_frame, text="源图片路径:", width=15, anchor='w').pack(side='left')
        self.source_entry = tk.Entry(source_frame, width=50)
        self.source_entry.pack(side='left', padx=5)
        ttk.Button(source_frame, text="浏览...", command=self.choose_source).pack(side='left')
        
        # 目标图片行
        target_frame = tk.Frame(main_frame)
        target_frame.pack(fill='x', pady=5, anchor='w')
        
        tk.Label(target_frame, text="目标图片路径:", width=15, anchor='w').pack(side='left')
        self.target_entry = tk.Entry(target_frame, width=50)
        self.target_entry.pack(side='left', padx=5)
        ttk.Button(target_frame, text="浏览...", command=self.choose_target).pack(side='left')
        
        # 替换按钮
        button_frame = tk.Frame(main_frame)
        button_frame.pack(fill='x', pady=20)
        ttk.Button(button_frame, text="替换图片", command=self.replace_image).pack(expand=True)
    
    def load_config(self):
        """加载配置"""
        if os.path.exists(config_file):
            with open(config_file, 'r') as f:
                config = json.load(f)
                self.source_dir = config.get("source_dir", "")
                self.target_dir = config.get("target_dir", "")
                self.source_entry.insert(0, self.source_dir)
                self.target_entry.insert(0, self.target_dir)
    
    def save_config(self):
        """保存配置"""
        config = {
            "source_dir": self.source_dir,
            "target_dir": self.target_dir
        }
        with open(config_file, 'w') as f:
            json.dump(config, f)
    
    def choose_source(self):
        """选择源图片"""
        self.source_dir = filedialog.askopenfilename(
            title="选择源图片",
            filetypes=[("Image Files", "*.jpg;*.jpeg;*.png;*.bmp")]
        )
        self.source_entry.delete(0, tk.END)
        self.source_entry.insert(0, self.source_dir)
    
    def choose_target(self):
        """选择目标图片"""
        self.target_dir = filedialog.askopenfilename(
            title="选择目标图片",
            filetypes=[("Image Files", "*.jpg;*.jpeg;*.png;*.bmp")]
        )
        self.target_entry.delete(0, tk.END)
        self.target_entry.insert(0, self.target_dir)
    
    def replace_image(self):
        """执行替换操作"""
        if not self.source_dir or not self.target_dir:
            messagebox.showerror("错误", "请先选择源图片和目标图片")
            return
        
        try:
            shutil.copy2(self.source_dir, self.target_dir)
            self.save_config()
            self.exit_code = 0  # 设置成功状态码
            self.root.quit()  # 退出主循环
        except Exception as e:
            self.exit_code = 1  # 保持失败状态码

def main():
    root = tk.Tk()
    app = ImageReplacerApp(root)
    root.mainloop()
    root.destroy()  # 确保窗口完全销毁
    return app.exit_code  # 返回状态码

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)  # 使用状态码退出程序